import Vue from 'vue'
import axios from 'axios'
 
import { Notification, Message, Loading } from 'element-ui'
import store from '@/store'
import errorCode from '@/utils/errorCode'
 
 
// let downloadLoadingInstance
// 是否显示重新登录
// export let isRelogin = { show: false };

axios.defaults.headers['X-Requested-With'] = 'XMLHttpRequest'
const service = axios.create({
  baseURL: window.config.baseUrl,
  timeout: 10000
})

// 请求拦截器
service.interceptors.request.use(config => {
  // 标记接口是否需要设置 token
  const isToken = (config.headers || {}).isToken === false

  if (store.state.app.token && !isToken) {
    config.headers.token = store.state.app.token // 请求头携带token
  }
  // get请求映射params参数
  if (config.method === 'get' && config.params) {
    let url = config.url + '?' + tansParams(config.params)
    url = url.slice(0, -1)
    config.params = {}
    config.url = url
  }
  return config
}, error => {
  console.error(error)
  Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(res => {
  // 未设置状态码则默认成功状态
  const code = res.data.responseStatus || res.status
  // 获取错误信息
  // console.log(JSON.stringify(res),'666');
  
  const msg = res.data.responseMessage || errorCode[code] || errorCode.default
  // 二进制数据则直接返回
  if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
    return res.data
  }
  if (code === 401 || code === 600 || code === 302) {
    // todo 需要登出
    Notification.error({ title: msg })
    Vue.prototype.$maicoReLogin()
    return Promise.reject(res)
  } else if (code !== 200) {
    Notification.error({ title: msg })
    return Promise.reject(res)
  } else {
    return res.data.responseData || res.data
  }
}, error => {
  console.log('err' + error)
  let { message } = error
  if (message === 'Network Error') {
    message = '网络或后端接口连接异常'
  } else if (message.includes('timeout')) {
    message = '系统接口请求超时'
  } else if (message.includes('Request failed with status code')) {
    message = '系统接口' + message.substr(message.length - 3) + '异常'
  }

  Message({ message: message, type: 'error', duration: 5 * 1000 })
  return Promise.reject(error)
})



/**
 * 参数处理
 * @param {*} params  参数
 */
export function tansParams (params) {
  let result = ''
  for (const propName of Object.keys(params)) {
    const value = params[propName]
    const part = encodeURIComponent(propName) + '='
    if (value !== null && value !== '' && typeof (value) !== 'undefined') {
      if (typeof value === 'object') {
        for (const key of Object.keys(value)) {
          if (value[key] !== null && value[key] !== '' && typeof (value[key]) !== 'undefined') {
            const params = propName + '[' + key + ']'
            const subPart = encodeURIComponent(params) + '='
            result += subPart + encodeURIComponent(value[key]) + '&'
          }
        }
      } else {
        result += part + encodeURIComponent(value) + '&'
      }
    }
  }
  return result
}


export default service
